<template>
  <a-spin :spinning="confirmLoading">
    <JFormContainer :disabled="disabled">
      <template #detail>
        <a-form ref="formRef" class="antd-modal-form" :labelCol="labelCol" :wrapperCol="wrapperCol" name="CContractorInfoForm">
          <a-row>
			  <a-divider >基础信息</a-divider >
						<a-col :span="12">
							<a-form-item label="供应商名称" v-bind="validateInfos.contactName" id="CContractorInfoForm-contactName" name="contactName">
								<a-input v-model:value="formData.contactName" placeholder="请输入供应商名称"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12"  v-show="false">
							<a-form-item label="id" v-bind="validateInfos.id" id="CContractorInfoForm-id" name="contactId">
								<a-input v-model:value="formData.id" placeholder="请输入id"  allow-clear ></a-input>
							</a-form-item>
						</a-col>

            <a-col :span="12" v-auth="'crm:bindPermissionUser'">
              <a-form-item label="指派权限用户" v-bind="validateInfos.userId" id="CContractorInfoForm-userId" name="userId">
                <j-dict-select-tag showSearch="true"   v-model:value="formData.userId"
                                   dictCode="sys_user,username,id" placeholder="请输入指派权限用户"  allow-clear />
              </a-form-item>
            </a-col>

            <a-col :span="12">
							<a-form-item label="联系人" v-bind="validateInfos.contactPerson" id="CContractorInfoForm-contactPerson" name="contactPerson">
								<a-input v-model:value="formData.contactPerson" placeholder="请输入联系人"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="联系电话" v-bind="validateInfos.contactPhone" id="CContractorInfoForm-contactPhone" name="contactPhone">
								<a-input v-model:value="formData.contactPhone" placeholder="请输入联系电话"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="供应商类型" v-bind="validateInfos.contactType" id="CContractorInfoForm-contactType" name="contactType">
								<a-input v-model:value="formData.contactType" placeholder="请输入供应商类型"  allow-clear ></a-input>
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="电子邮箱" v-bind="validateInfos.email" id="CContractorInfoForm-email" name="email">
								<a-input v-model:value="formData.email" placeholder="请输入电子邮箱"  allow-clear ></a-input>
							</a-form-item>
						</a-col>	
						
						<a-col :span="12">
							<a-form-item label="合作模式" v-bind="validateInfos.conspireMode" id="CContractorInfoForm-conspireMode" name="conspireMode">
								 <j-dict-select-tag showSearch="true"   v-model:value="formData.conspireMode" dictCode="conspireMode" placeholder="请选择任务合作模式"  allow-clear />
								
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="地址" v-bind="validateInfos.address" id="CContractorInfoForm-address" name="address">
								<a-textarea v-model:value="formData.address" :rows="4" placeholder="请输入地址" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="经营范围" v-bind="validateInfos.businessScope" id="CContractorInfoForm-businessScope" name="businessScope">
								<a-textarea v-model:value="formData.businessScope" :rows="4" placeholder="请输入经营范围" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="资质范围" v-bind="validateInfos.qualificationScope" id="CContractorInfoForm-qualificationScope" name="qualificationScope">
								<a-textarea v-model:value="formData.qualificationScope" :rows="4" placeholder="请输入资质范围" />
							</a-form-item>
						</a-col>
						<a-col :span="12">
							<a-form-item label="资质材料" v-bind="validateInfos.qualificationsFile" id="CProjectApplicationForm-qualificationsFile" name="qualificationsFile">
								<j-upload v-model:value="formData.qualificationsFile" dragger="true"   :show-upload-list="{ showDownloadIcon: true, showRemoveIcon: true }" text="上传"></j-upload>

							</a-form-item>
						</a-col>
								
          </a-row>
		  <a-divider >银行信息</a-divider >
		  <a-col :span="1000">
		  	<CheckRuleModal :contactId="formData.id"  :snapContactId="snapContactId"></CheckRuleModal>
		  </a-col>
        </a-form>
      </template>
    </JFormContainer>
  </a-spin>
</template>

<script lang="ts" setup>
  import { ref, reactive, defineExpose, nextTick, defineProps, computed, onMounted } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getValueType } from '/@/utils';
  import { saveOrUpdate } from '../CContractorInfo.api';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import JUpload from '/@/components/Form/src/jeecg/components/JUpload/JUpload.vue';
  import JImageUpload from '/@/components/Form/src/jeecg/components/JImageUpload.vue';
  import { Form } from 'ant-design-vue';
 
  import { getUserList } from '../../common.api';
  import JFormContainer from '/@/components/Form/src/container/JFormContainer.vue';
  import CheckRuleModal from '../../bankInfo/CBankInfoListInfo.vue';
  import { buildShortUUID } from '/@/utils/uuid';//uuid
  const props = defineProps({
    formDisabled: { type: Boolean, default: false },
    formData: { type: Object, default: () => ({})},
    formBpm: { type: Boolean, default: true }
  });
  const userList = ref([]);
  const formRef = ref();
  const useForm = Form.useForm;
  
  const snapContactId = ref(''); //临时id
  const emit = defineEmits(['register', 'ok']);
  const formData = reactive<Record<string, any>>({
    id: '',
    contactName: '',   
	 taxBank: '',  
	 taxName: '',  
	 taxId: '',
	 contactPerson: '',   
	taxBankAccount: '',  
    contactPhone: '',   
    address: '',   
    email: '',   
    bankAccount: '',   
    contactType: '',   
    subProjectId: '',   
	bankPerson:'',
	bankName:'',
	bankBranch:'',
	conspireMode:'综合',
	qualificationsFile:'',
	qualificationScope:'',
	businessScope:'',
    userId:'',

  });
  const { createMessage } = useMessage();
  const labelCol = ref<any>({ xs: { span: 24 }, sm: { span: 5 } });
  const wrapperCol = ref<any>({ xs: { span: 24 }, sm: { span: 16 } });
  const confirmLoading = ref<boolean>(false);
  //表单验证
  const validatorRules = reactive({
    contactName: [{ required: true, message: '请输入供应商名称!'},],
   // contactPerson: [{ required: true, message: '请输入联系人!'},],
   // contactPhone: [{ required: true, message: '请输入联系电话!'},],
   // address: [{ required: true, message: '请输入地址!'},],
  });
  const { resetFields, validate, validateInfos } = useForm(formData, validatorRules, { immediate: false });

  // 表单禁用
  const disabled = computed(()=>{
    if(props.formBpm === true){
      if(props.formData.disabled === false){
        return false;
      }else{
        return true;
      }
    }
    return props.formDisabled;
  });
	// const fetchUserList = async () => {
	//   try {
	// 	const response = await getUserList();
	// 	userList.value = response.map(item => ({
	// 	  label: item.realname,
	// 	  value: item.id
	// 	}));
	//   } catch (error) {
	// 	message.error('获取用户列表失败');
	// 	console.error('获取用户列表失败:', error);
	//   }
	// };
  
  /**
   * 新增
   */
  function add() {
	   formData.id = ""
	snapContactId.value = buildShortUUID('temporary_id_del')
	const defaultValueRef = reactive<Record<string, any>>({
		id: snapContactId.value,   
			})
    edit(defaultValueRef);
  }

  /**
   * 编辑
   */
  function edit(record) {

	  //fetchUserList();
    nextTick(() => {
      resetFields();
      const tmpData = {};
      Object.keys(formData).forEach((key) => {
        if(record.hasOwnProperty(key)){
          tmpData[key] = record[key]
        }
      })
      //赋值
      Object.assign(formData, tmpData);
    });


  }

  /**
   * 提交数据
   */
  async function submitForm() {
    try {
      // 触发表单验证
      await validate();
    } catch ({ errorFields }) {
      if (errorFields) {
        const firstField = errorFields[0];
        if (firstField) {
          formRef.value.scrollToField(firstField.name, { behavior: 'smooth', block: 'center' });
        }
      }
      return Promise.reject(errorFields);
    }
    confirmLoading.value = true;
    const isUpdate = ref<boolean>(false);
    //时间格式化
    let model = formData;

    if (model.id && !model.id.includes("temporary_id_del")) {
      isUpdate.value = true;
    }
    //循环数据
    for (let data in model) {
      //如果该数据是数组并且是字符串类型
      if (model[data] instanceof Array) {
        let valueType = getValueType(formRef.value.getProps, data);
        //如果是字符串类型的需要变成以逗号分割的字符串
        if (valueType === 'string') {
          model[data] = model[data].join(',');
        }
      }
    }
    await saveOrUpdate(model, isUpdate.value)
      .then((res) => {
        if (res.success) {
          createMessage.success(res.message);
          emit('ok');
        } else {
          createMessage.warning(res.message);
        }
      })
      .finally(() => {
        confirmLoading.value = false;
      });
  }


  defineExpose({
    add,
    edit,
    submitForm,
	snapContactId,
  });
</script>

<style lang="less" scoped>
  .antd-modal-form {
    padding: 14px;
  }
</style>
